// auth.js - 用户认证相关功能

// 全局变量
window.currentUser = null;

// 获取DOM元素
const loginBtn = document.getElementById('login-btn');
const registerBtn = document.getElementById('register-btn');
const logoutBtn = document.getElementById('logout-btn');
const loginModal = new bootstrap.Modal(document.getElementById('login-modal'));
const registerModal = new bootstrap.Modal(document.getElementById('register-modal'));
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const loginError = document.getElementById('login-error');
const registerError = document.getElementById('register-error');
const guestSection = document.querySelector('.guest-section');
const userSection = document.querySelector('.user-section');
const usernameDisplay = document.querySelector('.username-display');

// 登录功能
async function login(username, password) {
  try {
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '登录失败');
    }

    window.currentUser = data;
    console.log('用户登录成功:', window.currentUser);
    loginModal.hide();
    updateAuthUI();
    
    // 触发登录成功事件，其他模块可能需要监听
    document.dispatchEvent(new CustomEvent('userLoggedIn', { detail: window.currentUser }));
    
    // 清空表单
    loginForm.reset();
    return data;
  } catch (error) {
    loginError.textContent = error.message;
    loginError.classList.remove('d-none');
    throw error;
  }
}

// 注册功能
async function register(username, password, email) {
  try {
    const response = await fetch('/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password, email }),
      credentials: 'include',
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || '注册失败');
    }

    window.currentUser = data;
    console.log('用户注册成功:', window.currentUser);
    registerModal.hide();
    updateAuthUI();
    
    // 触发登录成功事件
    document.dispatchEvent(new CustomEvent('userLoggedIn', { detail: window.currentUser }));
    
    // 清空表单
    registerForm.reset();
    return data;
  } catch (error) {
    registerError.textContent = error.message;
    registerError.classList.remove('d-none');
    throw error;
  }
}

// 登出功能
async function logout() {
  try {
    const response = await fetch('/api/auth/logout', {
      method: 'POST',
      credentials: 'include',
    });

    if (!response.ok) {
      const data = await response.json();
      throw new Error(data.error || '登出失败');
    }

    window.currentUser = null;
    console.log('用户已登出');
    updateAuthUI();
    
    // 触发登出事件
    document.dispatchEvent(new CustomEvent('userLoggedOut'));
    
    // 回到首页
    document.dispatchEvent(new CustomEvent('navigateTo', { detail: { page: 'home' }}));
  } catch (error) {
    console.error('登出错误:', error);
    alert('登出失败: ' + error.message);
  }
}

// 获取当前用户信息
async function getCurrentUser() {
  try {
    const response = await fetch('/api/auth/me', {
      credentials: 'include',
    });

    if (!response.ok) {
      if (response.status === 401) {
        // 用户未登录
        console.log('用户未登录');
        return null;
      }
      throw new Error('获取用户信息失败');
    }

    const data = await response.json();
    window.currentUser = data;
    console.log('获取当前用户成功:', window.currentUser);
    return data;
  } catch (error) {
    console.error('获取用户信息错误:', error);
    return null;
  }
}

// 更新UI显示
function updateAuthUI() {
  if (window.currentUser) {
    // 已登录状态
    guestSection.classList.add('d-none');
    userSection.classList.remove('d-none');
    usernameDisplay.textContent = window.currentUser.username;
    
    // 移除可能的禁用状态
    document.querySelectorAll('.auth-required').forEach(el => {
      el.classList.remove('disabled');
      el.removeAttribute('disabled');
    });
    
    console.log('UI更新为已登录状态');
  } else {
    // 未登录状态
    guestSection.classList.remove('d-none');
    userSection.classList.add('d-none');
    usernameDisplay.textContent = '';
    
    // 禁用需要登录的功能
    document.querySelectorAll('.auth-required').forEach(el => {
      el.classList.add('disabled');
      el.setAttribute('disabled', 'true');
    });
    
    console.log('UI更新为未登录状态');
  }
}

// 事件监听
loginBtn.addEventListener('click', () => {
  console.log('点击登录按钮');
  loginError.classList.add('d-none');
  loginModal.show();
});

registerBtn.addEventListener('click', () => {
  console.log('点击注册按钮');
  registerError.classList.add('d-none');
  registerModal.show();
});

logoutBtn.addEventListener('click', logout);

loginForm.addEventListener('submit', async (e) => {
  e.preventDefault();
  console.log('提交登录表单');
  const username = document.getElementById('login-username').value;
  const password = document.getElementById('login-password').value;
  
  loginError.classList.add('d-none');
  
  try {
    await login(username, password);
  } catch (error) {
    // 错误已在login函数中处理
  }
});

registerForm.addEventListener('submit', async (e) => {
  e.preventDefault();
  console.log('提交注册表单');
  const username = document.getElementById('register-username').value;
  const password = document.getElementById('register-password').value;
  const confirmPassword = document.getElementById('register-password-confirm').value;
  const email = document.getElementById('register-email').value;
  
  registerError.classList.add('d-none');
  
  // 验证密码一致性
  if (password !== confirmPassword) {
    registerError.textContent = '两次输入的密码不一致';
    registerError.classList.remove('d-none');
    return;
  }
  
  try {
    await register(username, password, email);
  } catch (error) {
    // 错误已在register函数中处理
  }
});

// 页面加载时检查用户登录状态
document.addEventListener('DOMContentLoaded', async () => {
  console.log('DOM加载完成，检查用户登录状态');
  try {
    const user = await getCurrentUser();
    if (user) {
      window.currentUser = user;
      updateAuthUI();
      document.dispatchEvent(new CustomEvent('userLoggedIn', { detail: window.currentUser }));
    }
  } catch (error) {
    console.error('检查用户登录状态失败:', error);
  }
});

// 导出函数供其他模块使用
window.Auth = {
  getCurrentUser: () => window.currentUser,
  isLoggedIn: () => !!window.currentUser,
  login,
  logout,
  register,
}; 